package com.edu.dao.impl;

import com.edu.dao.UserDao;
import com.edu.entity.UserEntity;
import com.edu.utils.DatabaseManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {


    private Connection connection;

    public UserDaoImpl() {
        try {
            this.connection = DatabaseManager.getInstance().getConnection();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public boolean createUser(String username, String email, String password) {
        try {
            if (getUserByEmail(email) != null) {
                return false;
            }
            String sql = "INSERT INTO User (username, email, password_hash) VALUES (?, ?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, email);
            preparedStatement.setString(3, password);
            return preparedStatement.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public UserEntity getUserByEmailAndPassword(String email, String password) {
        try {
            String sql = "SELECT * FROM User WHERE email = ? AND password_hash = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, email);
            preparedStatement.setString(2, password);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                // Create and return User object
                return new UserEntity(resultSet.getInt("user_id"), resultSet.getString("username"), resultSet.getString("email"), resultSet.getString("password_hash"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public UserEntity getUserByEmail(String email) {
        try {
            String sql = "SELECT * FROM User WHERE email = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, email);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                // 创建并返回User对象，注意不要泄露敏感信息如密码hash到前端
                return new UserEntity(
                        resultSet.getInt("user_id"),
                        resultSet.getString("username"),
                        resultSet.getString("email")
                        // 注意：实践中通常不从数据库查询直接传递密码hash到客户端，故省略
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null; // 如果没有找到用户，返回null
    }

}